package com.imooc.animation360.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.graphics.Path;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.os.Build;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

public class MyProgressView extends View {
	private int width=150;
	private int height=150;
	private Paint circlePaint;
	private Paint progressPaint;
	private Paint textPaint;
	//空的Bitmap,本例是先将所有元素全部都绘制在这个空的Bitmap上,然后将这个Bitmap绘制到控件上.
	private Bitmap bitmap;
	//与上面的空Bitmap相关联的画布.
	private Canvas bitmapCanvas;
	//绘制波浪线与底部的闭合区域的路径对象.
	private Path path;
	private static final int PROGRESS_DEST = 100;  		//目标进度
	private static final int PROGRESS_MAX = 200;        //最大进度
	private int currentProgress=0;						//当前进度
	private String progressText;						//进度信息
	private static final int  AMPLITUDE_Y = 10; //画贝塞尔曲线时上下的振幅(控制点的y坐标的绝对值).
	/**用于更新进度显示.*/
	private Handler handler = new Handler();
	private static final int  WAVE_TIMES = 50; //单击后计划波动的次数.
	private int count=WAVE_TIMES; //单击后还剩余波动的次数,显然它是递减的.
	private boolean isSingleTap = false;

	public MyProgressView(Context context) {
		this(context,null);
	}

	public MyProgressView(Context context, AttributeSet attrs) {
		this(context, attrs,0);
	}

	public MyProgressView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}
	
	
	private void init(){
		//这个判断必须有,否则混合效果体现不出来.
		if(Build.VERSION.SDK_INT >= 11){
            setLayerType(LAYER_TYPE_SOFTWARE, null);
        }
		
		circlePaint = new Paint();
		circlePaint.setColor(Color.argb(0xff, 0x3a, 0x8c, 0x6c));
		circlePaint.setAntiAlias(true);
		
		progressPaint = new Paint();
		progressPaint.setColor(Color.argb(0xff, 0x4e, 0xc9, 0x63));
		progressPaint.setAntiAlias(true);
		progressPaint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); //只绘制重叠的部分.
		path = new Path();
		
		textPaint = new Paint();
		textPaint.setColor(Color.WHITE);
		textPaint.setAntiAlias(true);
		textPaint.setTextSize(25);
		
		//新建一个空的透明的画布.
		bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
		bitmapCanvas = new Canvas(bitmap);
		
		
		final GestureDetector mGestureDetector = new GestureDetector(new MyOnGestureListener());
		setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				return mGestureDetector.onTouchEvent(event);
			}
		});
		setClickable(true); //要能相应触摸事件,clickable和longClickable必须有1个位true.
	}
	
	
	
	class MyOnGestureListener extends SimpleOnGestureListener{
		@Override
		public boolean onSingleTapConfirmed(MotionEvent e) {
			startSingleAnimation();
			return super.onSingleTapUp(e);
		}
		@Override
		public boolean onDoubleTap(MotionEvent e) {
			startDoubleAnimation();
			return super.onDoubleTap(e);
		}
	}
	
	
	/**
	 * 单击动画-水波纹动画效果,当前进度固定在中心线处.
	 */
	public void startSingleAnimation(){
		isSingleTap = true;
		currentProgress=PROGRESS_DEST;
		handler.postDelayed(new SingleTapRunnable(), 200);
	}
	class SingleTapRunnable implements Runnable{

		@Override
		public void run() {
			count--;
			if(count>=0){
				handler.postDelayed(this, 200);
				invalidate();
			}else{
				handler.removeCallbacks(this);
				count=WAVE_TIMES;
			}
		}
	}
	
	/**
	 * 单击动画-水不断注入效果,当前进度由小到大递增.
	 */
	public void startDoubleAnimation(){
		isSingleTap = false;
		currentProgress=0;
		handler.postDelayed(new DoubleTapRunnable(), 50);
	}
	class DoubleTapRunnable implements Runnable{

		@Override
		public void run() {
			currentProgress++;
			if(currentProgress<=PROGRESS_DEST){
				handler.postDelayed(this, 50);
				invalidate();
			}else{
				handler.removeCallbacks(this);
				currentProgress=0;
			}
		}
	}
	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		setMeasuredDimension(width, height);
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		//将圆形绘制在新建的透明的画布上.
        bitmapCanvas.drawCircle(width/2, height/2, width/2, circlePaint);
		
		//绘制波浪线与圆圈下部的闭合区域,需要使用贝塞尔曲线.
		path.reset();  //reset一定要有,否则会出现诡异的黑色,设置什么混合模式都不管用.
		float y = (1-(float)currentProgress/PROGRESS_MAX)*height;  //右上角的点
		path.moveTo(width, y);
		path.lineTo(width, height);
		path.lineTo(0, height);
		path.lineTo(0, y);
		if(!isSingleTap){
			float  amplitudeY = (1-(float)currentProgress/PROGRESS_DEST)*AMPLITUDE_Y; 
			for(int i=0;i<5;i++){
				path.rQuadTo(10, -amplitudeY, 20, 0);
				path.rQuadTo(10, amplitudeY, 20, 0);
			}
		}else{
			float  amplitudeY = ((float)count/WAVE_TIMES)*AMPLITUDE_Y; 
			//贝塞尔曲线的方向来回颠倒,才能体现水波纹的效果.
			if(count%2==0){
				for(int i=0;i<5;i++){
					path.rQuadTo(10, -amplitudeY, 20, 0);
					path.rQuadTo(10, amplitudeY, 20, 0);
				}
			}else{
				for(int i=0;i<5;i++){
					path.rQuadTo(10, amplitudeY, 20, 0);
					path.rQuadTo(10, -amplitudeY, 20, 0);
				}
			}
		}
		path.close();
		bitmapCanvas.drawPath(path, progressPaint);
		 
		//绘制文本.
		progressText = (int)(((float)currentProgress/PROGRESS_MAX)*100) + "%";
		float textWidth = textPaint.measureText(progressText);
		float baseLinex = width/2-textWidth/2;
		FontMetrics fontMetrics = textPaint.getFontMetrics();
		float dy = -(fontMetrics.ascent+fontMetrics.descent)/2;
		float baseLiney = height/2+dy;
		bitmapCanvas.drawText(progressText, baseLinex, baseLiney, textPaint);
		
		//将bitmap绘制出来.
		canvas.drawBitmap(bitmap, 0, 0, null);
	}

}
